<template>
  <div ref="root" class="overflow-y-scroll overflow-x-hidden">
    <slot name="search">
      <div>
        <div class="mt-2 relative rounded-md shadow-sm">
          <input
            type="text"
            name="account-number"
            v-model="query.q"
            @input="onInput"
            class="
              ring-0
              focus:ring-0
              focus:border-0
              focus:outline-none
              block
              w-full
              pr-10
              sm:text-sm
              border-gray-300
              bg-transparent
              rounded-md
              text-white
            "
            placeholder=""
          />
          <div
            class="
              absolute
              inset-y-0
              right-0
              pr-3
              flex
              items-center
              pointer-events-none
            "
          >
            <SearchIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
          </div>
        </div>
      </div>
    </slot>
    <slot name="list" :data="data"></slot>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";
import { SearchIcon } from "@heroicons/vue/solid";
import debounce from "../../util/debounce";

export default defineComponent({
  components: {
    SearchIcon,
  },
  props: {
    useFetch: {
      type: Function,
      required: true,
    },
  },
  setup(props, { emit }) {
    const root = ref<HTMLDivElement>();
    // 查询关键字
    const { data, dataFetch, query } = props.useFetch as any;

    watch(data, () => {
      console.log("fetched data", data.value);
    });

    // 侦听搜索输入
    watch(query, async () => {
      console.log("query change", query);
      await dataFetch();
    });

    onMounted(async () => {
      const element = root.value;
      element!.addEventListener("scroll", handleScroll);
    });

    const handleScroll = (e: any) => {
      let element = root.value;
      // console.log(element.scrollHeight, element.scrollTop, element.clientHeight)
      if (
        element!.scrollHeight - element!.scrollTop ===
        element!.clientHeight
      ) {
        console.log("bottom");
        dataFetch();
        emit("scrollToBottom", { e });
      }
    };

    const onInput = () => {
      debounce(() => {
        dataFetch();
        query.start += 1;
      }, 300)();
    };

    return {
      root,
      query,
      handleScroll,
      data,
      onInput,
    };
  },
});
</script>
